package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.entity.Address;
import com.qf.enums.ApiEnum;
import com.qf.exception.GlobalException;
import com.qf.mapper.AddressMapper;
import com.qf.service.IAddressService;
import com.qf.utils.IdWorker;
import com.qf.utils.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 地址表 服务实现类
 * </p>
 *
 * @author chen
 * @since 2021-03-23
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {

    @Resource
    private AddressMapper addressMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeDefault(String id) {
        //原本的移除
        addressMapper.clearAddressDefault(Long.parseLong(UserUtils.getUser().get("id").toString()));

        //设置地址默认
        addressMapper.setAddressDefault(id,Long.parseLong(UserUtils.getUser().get("id").toString()));

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Address address) {

        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",UserUtils.getUser().get("id"));
        Integer integer = addressMapper.selectCount(queryWrapper);
        if(integer > 5){
            throw new GlobalException(ApiEnum.ADDRESS_TOO_MANY);
        }


        IdWorker idWorker = new IdWorker(1,1,1);
        address.setId(idWorker.nextId());
        address.setCreateTime(new Date());
        address.setUpdateTime(new Date());
        address.setUserId(Long.parseLong(UserUtils.getUser().get("id").toString()));
        addressMapper.insert(address);
        this.changeDefault(address.getId().toString());
    }
}
